const _ = require('lodash');
const async = require('async');
const commonService = require('../common');

function getList(params, callback) {
  const { SysRole: roleModel } = commonService.getModels();
  const pageNumber = _.toNumber(params.pageNumber);
  const pageSize = _.toNumber(params.pageSize);
  const name = params.name ? params.name : '';
  if (params.isSuperUser === 'true') {
    const filter = {
      limit: pageSize,
      skip: pageSize * (pageNumber - 1),
    };
    commonService.getList(roleModel, filter, callback);
  } else if (!_.isEmpty(params.userFormIds)) {
    let sql = `SELECT * FROM elanco_sys.sys_role 
                 WHERE sys_deleted = false `;
    name ? sql += ` AND name like '%${name}%' ` : '';
    sql += `AND (SELECT ARRAY(SELECT (jsonb_array_elements_text(others->'formIds'))::int) && ARRAY[${params.userFormIds}]) AND (SELECT ARRAY(SELECT (jsonb_array_elements_text(others->'formIds'))::int) && ARRAY[${params.userFormIds}])  ORDER BY id OFFSET ${pageSize * (pageNumber - 1)} LIMIT ${pageSize};`;
    commonService.executeSql(sql, [], {}, callback);
  } else {
    callback(null, []);
  }
}

function getPageTotal(params, callback) {
  const { SysRole: roleModel } = commonService.getModels();
  const pageSize = _.toNumber(params.pageSize);
  const name = params.name ? params.name : '';
  if (params.isSuperUser === 'true') {
    commonService.getCount(roleModel, (error, count) => callback(error, _.ceil(count / pageSize)));
  } else if (!_.isEmpty(params.userFormIds)) {
    const getListCount = (next) => {
      let sql = `SELECT COUNT(id) FROM elanco_sys.sys_role 
                   WHERE (SELECT ARRAY(SELECT (jsonb_array_elements_text(others->'formIds'))::int) && ARRAY[${params.userFormIds}]) `;
      name ? sql += ` AND name like '%${name}%' ` : '';
      sql += ' AND sys_deleted = false;';
      commonService.executeSql(sql, [], {}, next);
    };
    async.waterfall([getListCount], (error, data) => {
      callback(error, _.ceil(_.toNumber(data[0].count) / _.toNumber(params.pageSize)));
    });
  } else {
    callback(null, 0);
  }
}

module.exports = {
  getList,
  getPageTotal,
};
